package com.von.nhcf.mvc.controller;

import com.github.pagehelper.PageInfo;
import com.von.nhcf.constant.NhcfConstant;
import com.von.nhcf.entity.Admin;
import com.von.nhcf.exception.AdminOnlineProjectException;
import com.von.nhcf.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 管理员控制器
 * @author von
 */
@Controller
public class AdminController {
    @Autowired
    AdminService adminService;

    @RequestMapping(value = "admin/do/edit.html", method = RequestMethod.POST)
    public String doEditAdmin(Admin admin, @RequestParam("pageNum") Integer pageNum,
                              @RequestParam("keyword") String keyword) {
        // 执行更新操作
        adminService.updateAdminSelective(admin);
        return "redirect:/admin/do/paging.html?pageNum=" + pageNum + "&keyword=" +keyword;
    }
    /**
     * 通过id获取对应的admin，跳转到处理页面
     * @param adminId
     * @param modelMap
     * @return
     */
    @PreAuthorize("hasAuthority('user:get')")
    @RequestMapping(value = "admin/to/edit/page.html")
    public String toEditAdminById(@RequestParam("adminId")Integer adminId, ModelMap modelMap) {
        // 通过id查询admin
        Admin admin = adminService.getAdminById(adminId);
        // 装载admin
        modelMap.addAttribute("admin", admin);

        return "admin_edit";
    }
    /**
     * 添加管理员
     * @param admin
     * @return
     */
    @RequestMapping(value = "admin/do/add.html", method = RequestMethod.POST)
    public String doAddAdmin(Admin admin) {
        adminService.saveAdmin(admin);
        // 重定向到分页页面， 使用重定向是为了避免刷新浏览器重复提交表单，MAX_VALUE是为了可以总是定位到最后一页
        return "redirect:/admin/do/paging.html?pageNum="+Integer.MAX_VALUE;
    }
    /**
     * 按照id删除对应的管理员记录
     * @param adminId
     * @param pageNum
     * @param keyword
     * @return
     */
    @RequestMapping(value = "/admin/do/delete/{adminId}/{pageNum}/{keyword}.html")
    public String doDeleteByAdminId(@PathVariable("adminId")Integer adminId, @PathVariable("pageNum")Integer pageNum,
                                    @PathVariable("keyword")String keyword, HttpSession session, HttpServletRequest request) {
        // 检查删除的记录是否为当前已登录的管理员
        Admin admin = (Admin)session.getAttribute(NhcfConstant.ATTR_NAME_LOGIN_ADMIN);
        if (admin.getId().equals(adminId)) {
            request.setAttribute("pageNum", pageNum);
            request.setAttribute("pageSize", 5);
            request.setAttribute("keyword", keyword);
            throw new AdminOnlineProjectException(NhcfConstant.MESSAGE_ADMIN_ONLINE_PROJECT);
        }
        // 执行删除操作
        adminService.deleteById(adminId);
        // 重定向页面
        return "redirect:/admin/do/paging.html?pageNum=" + pageNum + "&keyword=" +keyword;
    }

    /**
     * 分页控制器，可进行带关键字和不带关键字的分页
     * @param keyword 关键字
     * @param pageNum 页码，PageHelper的页码从1开始，每页第一项数据索引计算公式为index=(pageNum - 1)*pageSize
     * @param pageSize 每页显示的数据条数
     * @param modelMap 数据模型，以键值对的形式存入需要前端回显的数据
     * @return
     */
    // @PreAuthorize("hasAnyAuthority('经理操作者', '部长操作者')")
    @RequestMapping(value = "/admin/do/paging.html")
    public String getPageInfo(@RequestParam(value = "keyword", defaultValue = "")String keyword,
                              @RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "5")Integer pageSize,
                              ModelMap modelMap) {
        // 查询得到分页数据
        PageInfo<Admin> pageInfo = adminService.getPageInfo(keyword, pageNum, pageSize);
        // 将分页数据存入模型
        modelMap.addAttribute(NhcfConstant.ATTR_NAME_PAGE_INFO, pageInfo);
        return "admin_page";
    }
    /**
     * 管理员退出登录api
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/do/logout.html", method = RequestMethod.GET)
    public String doLogout(HttpSession session) {
        // session失效即可退出登录状态
        session.invalidate();

        return "redirect:/admin/to/login/page.html";
    }

    /**
     * 管理员登录api
     * @param loginAcct : 管理员账号
     * @param userPswd : 管理员密码
     * @param session
     * @return : 登录处理页面
     */
    @RequestMapping(value = "admin/do/login.html", method = RequestMethod.POST)
    public String doLogin(@RequestParam("loginAcct") String loginAcct, @RequestParam("userPswd") String userPswd,
                          HttpSession session) {
        // 检查管理员的登录账户是否存在，如果存在则检查密码是否正确
        Admin admin = adminService.getAdminByLoginAcct(loginAcct, userPswd);
        // 将登录成功的admin对象存入session域中
        session.setAttribute(NhcfConstant.ATTR_NAME_LOGIN_ADMIN, admin);

        // 重定向到管理员主页面
        return "redirect:/admin/to/main/page.html";
    }
}
